package com.itheima.controller;

import com.itheima.common.R;
import com.itheima.entity.Category;
import com.itheima.entity.Page;
import com.itheima.service.CategoryService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired(required = false)
    private CategoryService categoryService;


    @PostMapping
    //返回成功信息，浏览器传过来category和通过登录用户id添加信息
    public R<String> save(@RequestBody Category category, HttpSession session){
        long employee = (long) session.getAttribute("employee");

        category.setCreateUser(employee);

        category.setUpdateUser(employee);
        categoryService.save(category);
        return R.success("新增分类成功");
    }

    /**
     * 分页
     * @param page 当前页
     * @param pageSize 页面大小
     * @return
     */

    @GetMapping("/page")
    public R<Page<Category>> save(Integer page,Integer pageSize){
      Page<Category> pageResult =  categoryService.findByPage(page,pageSize);
      return R.success(pageResult);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping
    public R<String> delete(long id){
        categoryService.deleteById(id);

        return R.success("删除成功");
    }

    /**
     * 修改
     * @param category
     * @param session
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category,HttpSession session){
        long employee = (long) session.getAttribute("employee");
        category.setUpdateUser(employee);
        categoryService.updateById(category);
        return R.success("修改成功");

    }
/**
 * 作用：根据Type查询类别集合
 * @param type  类别的type
 * @return
 */
@GetMapping("list")
    public R<List<Category>> list(Integer type){
  List<Category> categoryList=  categoryService.list(type);
  return R.success(categoryList);
}


}
